import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:situation/data/channel/intercom_channel.dart';
import 'package:situation/data/request/base_request.dart';
import 'package:situation/domain/chat/msg.dart';
import 'package:situation/domain/common/UploadImageDto.dart';
import 'package:situation/shared/shared.dart';
import 'package:situation/shared/util/util_mk.dart';
// import 'package:wechat_assets_picker/wechat_assets_picker.dart';
// import 'package:wechat_camera_picker/wechat_camera_picker.dart';
import 'package:wukongimfluttersdk/entity/channel.dart';
import 'package:wukongimfluttersdk/entity/msg.dart';
import 'package:wukongimfluttersdk/model/wk_image_content.dart';
import 'package:wukongimfluttersdk/model/wk_text_content.dart';
import 'package:wukongimfluttersdk/model/wk_video_content.dart';
import 'package:wukongimfluttersdk/type/const.dart';
import 'package:wukongimfluttersdk/wkim.dart';

import 'state.dart';

class CommunicationChatController extends GetxController {
  final CommunicationChatState state = CommunicationChatState();

  TextEditingController textEditingController = TextEditingController();

  ScrollController scrollController = ScrollController();
  final channelID = Get.arguments['idcard'];
  final channelType = WKChannelType.personal;
  final remoteId = Get.arguments["remoteId"];
  final remoteName = Get.arguments["remoteName"];
  final remoteHeadImgUrl = Get.arguments["remoteHeadImgUrl"];
  final name = Get.arguments["name"];

  void changeVisible() {
    state.visible = !state.visible;
  }

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();

    print(Get.arguments);

    textEditingController.addListener(() {
      if (textEditingController.text.length > 0) {
        state.inTyping = true;
      } else {
        state.inTyping = false;
      }
    });
    initMsg();
    getMsgList(0, 0, true);
  }

  getPrevious() {
    var oldOrderSeq = 0;
    for (var msg in state.messages) {
      if (oldOrderSeq == 0 || oldOrderSeq > msg.wkMsg.orderSeq) {
        oldOrderSeq = msg.wkMsg.orderSeq;
      }
    }
    getMsgList(oldOrderSeq, 0, false);
  }



  initMsg() async {
    // 监听刷新频道
    WKIM.shared.channelManager.addOnRefreshListener('chat', (channel) {
      if (channelID == channel.channelID) {
        // title = channel.channelName;
      }
      for (var i = 0; i < state.messages.length; i++) {
        if (state.messages[i].wkMsg.fromUID == channel.channelID) {
          state.messages[i].wkMsg.setFrom(channel);
        }
      }
    });

    // 监听发送消息入库返回
    WKIM.shared.messageManager.addOnMsgInsertedListener((wkMsg) {
      state.messages.add(UIMsg(wkMsg));
      state.messages = state.messages.toList();

    });

    // 监听新消息
    WKIM.shared.messageManager.addOnNewMsgListener('chat', (msgs) {
      print('收到${msgs.length}条新消息');
      for (var i = 0; i < msgs.length; i++) {
        if (msgs[i].channelID != channelID) {
          continue;
        }
        if (msgs[i].setting.receipt == 1) {
          // 消息需要回执
          testReceipt(msgs[i]);
        }
        if (msgs[i].isDeleted == 0) {
          state.messages.add(UIMsg(msgs[i]));
          state.messages = state.messages.toList();
          // scrollController 移动到最底部
          // 0.5秒后执行
          Future.delayed(Duration(milliseconds: 500), () {
            scrollController.animateTo(
              scrollController.position.maxScrollExtent,
              duration: Duration(milliseconds: 200),
              curve: Curves.easeInOut,
            );
          });
        }
      }
    });

    // 监听上传消息附件
    WKIM.shared.messageManager.addOnUploadAttachmentListener((wkMsg, back) {
      back(true,wkMsg);
    });
    // 监听消息刷新
    WKIM.shared.messageManager.addOnRefreshMsgListener('chat', (wkMsg) {
      for (var i = 0; i < state.messages.length; i++) {
        if (state.messages[i].wkMsg.clientMsgNO == wkMsg.clientMsgNO) {
          state.messages[i].wkMsg.messageID = wkMsg.messageID;
          state.messages[i].wkMsg.messageSeq = wkMsg.messageSeq;
          state.messages[i].wkMsg.status = wkMsg.status;
          state.messages[i].wkMsg.wkMsgExtra = wkMsg.wkMsgExtra;
          break;
        }
      }
    });

    // 监听删除消息
    WKIM.shared.messageManager.addOnDeleteMsgListener('chat', (clientMsgNo) {
      for (var i = 0; i < state.messages.length; i++) {
        if (state.messages[i].wkMsg.clientMsgNO == clientMsgNo) {
          state.messages.removeAt(i);
          break;
        }
      }
    });

    // 清除聊天记录
    WKIM.shared.messageManager.addOnClearChannelMsgListener("chat", (channelId,
        channelType,) {
      if (channelID == channelId) {
        state.messages.clear();
      }
    });
  }

  getMsgList(int oldestOrderSeq, int pullMode, bool isReset) {
    WKIM.shared.messageManager.getOrSyncHistoryMessages(
      channelID,
      channelType,
      oldestOrderSeq,
      oldestOrderSeq == 0,
      pullMode,
      5,
      0,
          (list) {
        print('同步完成${list.length}条消息');
        List<UIMsg> uiList = [];
        for (int i = 0; i < list.length; i++) {
          if (pullMode == 0 && !isReset) {
            uiList.add(UIMsg(list[i]));
            // msgList.insert(0, UIMsg(list[i]));
          } else {
            state.messages.add(UIMsg(list[i]));
            state.messages = state.messages.toList();
          }
        }
        if (uiList.isNotEmpty) {
          state.messages.insertAll(0, uiList);
          state.messages = state.messages.toList();
        }
      },
          () {
        print('消息同步中');
      },
    );
  }

  testReceipt(WKMsg wkMsg) async {
    if (wkMsg.viewed == 0) {
      var maxVersion = await WKIM.shared.messageManager
          .getMaxExtraVersionWithChannel(channelID, channelType);
      var extra = WKMsgExtra();
      extra.messageID = wkMsg.messageID;
      extra.channelID = channelID;
      extra.channelType = channelType;
      extra.readed = 1;
      extra.readedCount = 1;
      extra.extraVersion = maxVersion + 1;
      List<WKMsgExtra> list = [];
      list.add(extra);
      WKIM.shared.messageManager.saveRemoteExtraMsg(list);
    }
  }

  void handleSend() {
    // 发送消息
    if (textEditingController.text.length == 0) {
      SmartDialog.showToast("请输入内容");
      return;
    }
    WKChannel wkChannel = WKChannel(channelID, channelType);
    WKTextContent text = WKTextContent(textEditingController.text);
    WKIM.shared.messageManager.sendMessage(text, wkChannel);
    textEditingController.text = "";
    initMsg();
  }

  uploadPic() async {
    final ImagePicker picker = ImagePicker();
    await UtilPermission.requestCaremaPermission();
    Get.bottomSheet(
      CupertinoActionSheet(
        actions: <Widget>[
          CupertinoActionSheetAction(
            child: const Text('拍照'),
            onPressed: () async {
              final XFile? photo = await picker.pickImage(source: ImageSource.camera);
              if (photo != null) {
                // 文件上传
                await upload(photo,"img");
              }
              Get.back();
            },
          ),
          CupertinoActionSheetAction(
            child: const Text('从相册选择'),
            onPressed: () async {
              final XFile? photo = await picker.pickImage(source: ImageSource.gallery);
              if (photo != null) {
                // 文件上传
                await upload(photo,"img");
              }
              Get.back();
            },
          ),
        ],
        cancelButton: CupertinoActionSheetAction(
          child: const Text('取消'),
          onPressed: () {
            Get.back();
          },
        ),
      ),
    );
  }

  Future<void> upload(XFile entity,String type) async {
    SmartDialog.showLoading(msg: '上传中...');

    SmartDialog.showLoading(msg: '上传中...');
    UploadImageDto uploadImageDto = await BaseRequest.uploadFile(entity.path);
    var length =await  entity.length();

    // 通过文件路径截取文件名称
    if (type == "img") {
      // 定义图片消息
      WKImageContent image = WKImageContent(100, 100);
      image.localPath = entity!.path; // 图片本地路径
      image.url = uploadImageDto.path!;
      // 发送图片消息
      WKIM.shared.messageManager.sendMessage(
        image,
        new WKChannel(channelID, channelType),
      );
    } else {
      String filePath = await UtilMk.getThumbnal(entity.path);

      UploadImageDto thumbImg = await BaseRequest.uploadFile(filePath);

      WKVideoContent video = WKVideoContent();
      video.localPath = entity.path; // 视频本地路径
      video.url = uploadImageDto.path!;
      video.cover = thumbImg.path!;
      video.second = 1;
      // 发送视频消息
      WKIM.shared.messageManager.sendMessage(
        video,
        new WKChannel(channelID, channelType),
      );
    }
    Future.delayed(Duration(milliseconds: 500), () {
      scrollController.animateTo(
        scrollController.position.maxScrollExtent,
        duration: Duration(milliseconds: 200),
        curve: Curves.easeInOut,
      );
    });

    SmartDialog.dismiss();
  }

  uploadVideo() async {
    final ImagePicker picker = ImagePicker();
    await UtilPermission.requestCaremaPermission();
    Get.bottomSheet(
      CupertinoActionSheet(
        actions: <Widget>[
          CupertinoActionSheetAction(
            child: const Text('拍照'),
            onPressed: () async {
              final XFile? photo = await picker.pickVideo(source: ImageSource.camera);
              if (photo != null) {
                // 文件上传
                await upload(photo,"img");
              }
              Get.back();
            },
          ),
          CupertinoActionSheetAction(
            child: const Text('从相册选择'),
            onPressed: () async {
              final XFile? photo = await picker.pickVideo(source: ImageSource.gallery);
              if (photo != null) {
                // 文件上传
                await upload(photo,"img");
              }
              Get.back();
            },
          ),
        ],
        cancelButton: CupertinoActionSheetAction(
          child: const Text('取消'),
          onPressed: () {
            Get.back();
          },
        ),
      ),
    );
  }

  FutureOr onLoad() async {}

  @override
  void onClose() {
    // TODO: implement onClose
    WKIM.shared.messageManager.removeNewMsgListener('chat');
    WKIM.shared.messageManager.removeOnRefreshMsgListener('chat');
    WKIM.shared.messageManager.removeDeleteMsgListener('chat');
    WKIM.shared.channelManager.removeOnRefreshListener('chat');

    super.onClose();
  }

  // 语音呼叫
  void voiceCall() {
    IntercomChannel.to.sendMsg({
      "event": IntercomChannel.to.EVENT_VOICE_CALL,
      "convId": remoteId,
      "convName": remoteName,
    });
  }

  // 视频通话
  void videoCall() async {
    var caremaGrant = await UtilPermission.requestCaremaPermission();
    if (!caremaGrant) {
      SmartDialog.showToast("请允许摄像头权限");
      return;
    }
    var micGrant = await UtilPermission.requestMicrophonePermission();
    if (!micGrant) {
      SmartDialog.showToast("请允许麦克风权限");
      return;
    }

    IntercomChannel.to.sendMsg({
      "event": IntercomChannel.to.EVENT_VIDEO_CALL,
      "convId": remoteId,
      "convName": remoteName,
    });
  }
}
